package com.sholmes.android.scribbler;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


/**
 * This is the main panel the user is presented with when starting the application.
 * 	You have 3 options:
 * 		1) Connect/Disconnect to a Robot.
 * 		2) Select Auto Behaviors
 * 		3) Select Manual Drive.
 * 
 * 	Option 1)
 * 		When you select to connect to the robot a device selection menu
 * 		is presented to the user.  Once a robot is selected to connect to
 * 		a panel on the top of the screen will indicate that we are currently
 * 		'Connecting..." this will either change to 'Connected: HWADDR' or 
 * 		'Disconnected' showing a message to the user that we were unable to 
 * 		connect.  Once connected the 'Connect' button goes away showing a 
 * 		'Disconnect' button.
 * 
 * 	Option 2)
 * 		This button will only become available once you are connected.  Selecting
 * 		this button will take you to another display activity 'AutoActivity'.
 * 
 *  Option 3)
 *  	This button will only become available once you are connected.  Selecting
 *  	this button will take you to another display activity 'ManualDriveActivity'.
 *  
 *  
 *  Look and feel)
 *  	Blue brushed metal background with scribbler written skewed across the 
 *  	  upper left corner. 
 *  
 *  	3 Buttons on the RHS of the view.
 *  
 *  	Text across the bottom indicating if connected/connecting/disconnected
 *  
 * 		Device locked into horizontal mode without a title bar in fullscreen. 
 *  
 *  	TODO: Play Daftpunk robot song in background lightly.
 *  	
 *  	TODO: On button clicks play noise.
 *  
 *  	TODO: Have animation of robot driving across screen.
 *  
 * @author Justin A. McCoy {@link mailto:justin.mccoy@acm.org}
 * 
 * 
 */
public class ScribblerActivity extends BasicRobotActivity{
	private static final String TAG = "------>ScribblerActivity: ";
	private Button mConnectDisconnectButton;
	private Button mAutoBehaviorsButton;
	private Button mManualDriveButton;
	
	
	
	protected static final int MESSAGE_STATE_CHANGE = 1;
	protected static final int MESSAGE_DEVICE_NAME = 2;
	protected static final int MESSAGE_TOAST = 3;
	
	//Key names received for the bluetoothService
	public static final String DEVICE_NAME = "device_name";
	public static final String TOAST = "toast";
	
	// Intent request codes
	private static final int REQUEST_CONNECT_DEVICE = 1;
	
	private boolean connected = false;
	//Display if we are connected/disconnected/connecting
	private TextView mStatusTextView;
	

	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scribbler);
        init();				//Sets up UI Elements  
    }
    
    
    
    /**
     * Setup the interface to the scribbler UI Activity Elements
     */
    private void init(){    	
    	mConnectDisconnectButton = (Button)findViewById(R.id.connectDisconnectButton);
    	mAutoBehaviorsButton = (Button)findViewById(R.id.autoBehaviorsButton);
    	mManualDriveButton = (Button)findViewById(R.id.manualDriveButton);
    	
    	mStatusTextView = (TextView)findViewById(R.id.statusText);
    	

    	/** Setting up Button Click Listeners **/
    	/**						  			  **/
    	
    	mConnectDisconnectButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {				
				if(!connected){	//If we are not connected need to connect					
					
					// Launch the DeviceListActivity to see devices and do scan
					Intent serverIntent = new Intent(ScribblerActivity.this,
							DeviceListActivity.class);
					startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
				}else{				
					
					// Disconnect from the robot by calling the Scribbler Service disconnect()					
					try {
						Log.d(TAG,"Service disconnecting");
						service.disconnect();
					} catch (RemoteException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
    	
    	mAutoBehaviorsButton.setOnClickListener(new OnClickListener() {
			//Load the AutoBehaviorsActivity View
    		@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(ScribblerActivity.this, AutoBehaviorActivity.class);
				startActivity(intent);
			}
		});
    
    	mManualDriveButton.setOnClickListener(new OnClickListener() {
			//Load the ManualDriveActivity View
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(ScribblerActivity.this, ManualDriveActivity.class);
				startActivity(intent);				
			}
		});    	
    	
    	
    	//Until we are connect to the robot these activities are disabled.
    	mAutoBehaviorsButton.setEnabled(false);
    	mManualDriveButton.setEnabled(false);
    }

    
    /**
     * When the user selects either the home or back button from the main screen
     * we need to disconnect from the robot so its not left in a funky state.
     */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		//if the user is exiting the program it is proper to disconnect from the robot
		if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) { 
			if(connected){					
				disconnect();					
			}
			return true;		// True indicates that the event has been handled.
		}else{					// Handle all other events.
			return super.onKeyDown(keyCode, event);
		}		
	}
    
    


    
	/**
	 * 
	 * 
	 * @param requestCode
	 * @param resultCode
	 * @param data
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CONNECT_DEVICE:
			// When DeviceListActivity returns with a device to connect
			if (resultCode == Activity.RESULT_OK) {

				// Get the selected devices MAC address 
				String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS); 
				
				//Connect to the selected device.
				//Upon success the bluetoothService will notify all observers that it has connected
				// or return a error why it didn't connect.									
			
				// Farm out the bluetooth connection handling to a Scribbler Service :) 
				Log.d(TAG,"Connecting to: "+ address);
				connect(address);		
			}
			break;
		}
	}



	
	private void connect(String deviceAddress){
		try {
			service.connect(deviceAddress);
		} catch (RemoteException e) {
			Log.e(TAG, "Error calling Scribbler Service connect.  See stack trace for more details.");
			e.printStackTrace();	
			//We do not exit here for the user can try connecting another time.
		}
	}
	
	private void disconnect(){
		try{
			service.disconnect();
			_disconnect();
		}catch (RemoteException e){
			Log.e(TAG, "Error calling Scribbler Service.disconnect. See stack trace for more details.");			
			e.printStackTrace();
			finish();			//If the disconnect failed.  Lets exit this Activity and Kill the service.
		}
	}
	
	
	/**
	 * Handle view elements when state moves to disconnected.
	 */
    protected void _disconnect(){    	
    	mStatusTextView.setText("Disconnected...");    	
		mAutoBehaviorsButton.setEnabled(false);
		mManualDriveButton.setEnabled(false);
		mConnectDisconnectButton.setText("Connect");
		mConnectDisconnectButton.setEnabled(true);
		connected = false;		
    }

	/**
	 * Handle view elements when state moves to connected.
	 */
	protected void _connected(String deviceAddress){
		mStatusTextView.setText("Connected: "+deviceAddress);
		mAutoBehaviorsButton.setEnabled(true);
		mManualDriveButton.setEnabled(true);
		mConnectDisconnectButton.setText("Disconnect");
		mConnectDisconnectButton.setEnabled(true);
		connected = true;
	}
	
	/**
	 * Handle view elements when state moves to connecting.
	 */
	protected void _connecting(String deviceAddress){
		mStatusTextView.setText("Connecting to: " + deviceAddress);
		mConnectDisconnectButton.setEnabled(false);
		mConnectDisconnectButton.setText("Connecting");
	}
	
	
	
	/** Called when the activity is about to be destroyed. */
	@Override
	protected void onDestroy(){
		Log.d(TAG,"onDestroy: Killing the RobotBluetoothService background process");		
		killService();		
		super.onDestroy();
	}		  
}